<template>
  <div>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      append-to-body
      class="small-common-dialog-size operator-dialog">
      <div class="quote-container">
        <div class="quote-formula-list">
          <div class="formula-list-item" style="margin-right:10px;">
            <div class="label">计算公式</div>
            <el-tooltip v-if="item.options && item.options.length" popper-class="tooltip-formula" class="item" placement="top" effect="light">
              <div slot="content" style="width: 240px;">
                <div class="tip-text">元素可进行拖拽排序</div>
                <draggable
                  v-model="item.options"
                  v-bind="dragOptions"
                  group="order"
                  class="formula-container-draggable"
                  handle=".draggable-move">
                  <transition-group type="transition" class="tooltip-formula-content">
                    <span
                      v-for="(tag, index) in item.options"
                      :key="index + tag.name"
                      class="formula-option-tag draggable-move"
                      @click.stop="deleteFormula(item, index)" > {{ tag.name }} </span>
                  </transition-group>
                </draggable>
              </div>
              <div :class="{'active': item.isFocus}" class="formula-option" @click.stop="toFocus(item)" >
                <div
                  v-for="(tag, index) in item.options"
                  :key="index"
                  class="formula-option-tag"
                  @click.stop="deleteFormula(item, index)">{{ tag.name }}</div>
              </div>
            </el-tooltip>
            <div v-else :class="{'active': item.isFocus}" class="formula-option" @click.stop="toFocus(item)" >
              <div
                v-for="(tag, index) in item.options"
                :key="index"
                class="formula-option-tag"
                @click.stop="deleteFormula(item, index)">{{ tag.name }}</div>
            </div>
          </div>
          <!-- 引用字段 -->
          <div class="formula-list-item" style="margin-right:10px;">
            <div class="label">数据引用</div>
            <el-cascader
              v-model="cascaderValue"
              :options="fieldList"
              :props="{
                value: 'name',
                label: 'name',
                children: 'fieldInfo'
              }"
              placeholder="选择字段"
              class="filterableSelect"
              filterable
              clearable
              @change="filedSelect" />
          </div>
          <!-- 引用数值 -->
          <div class="formula-list-item">
            <div class="label" style="width:84px;">数值</div>
            <div class="quote-input">
              <el-input v-model="quoteValue" placeholder="请输入数字，可输入小数点" type="number" />
            </div>
            <el-button type="text" size="small" style="margin-left:10px;" @click="quoteFun({name: quoteValue, id: Number(quoteValue),postName: null}, 'clearQuoteValue')">填入</el-button>
          </div>
        </div>
        <div v-if="isQuoteTemplateField" class="quote-formula-list">
          <el-select v-model="quoteTemplateField" value-key="id" class="filter-120" popper-class="global-select-down" placeholder="请选择临时字段" name="filterField">
            <el-option
              v-for="item in fieldListOpt"
              :key="item.id"
              :label="item.name"
              :value="item" />
          </el-select>
          <el-button
            size="small"
            type="text"
            style="margin-left:10px;"
            @click="quoteFun({
              name: quoteTemplateField.name,
              id: quoteTemplateField.id,
              isVariate: true,
              postName: JSON.stringify(quoteTemplateField.name)},'clearquoteTemplateField')">引用</el-button>
        </div>
        <div class="quote-list">
          <div class="quote-title" style="margin-right: 12px;">计算元素</div>
          <div
            v-for="(item, index) in mathTag"
            :key="index"
            class="quote-tag"
            @click="quoteFun(item, 'math')"
          >{{ item.name }}</div>
        </div>
      </div>
      <div class="center btns">
        <el-button class="ok submit-btn" type="primary" size="small" @click="handleConfirm">确定</el-button>
        <el-button class="back-btn cancel-btn-style" size="small" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: { draggable },
  props: {
    isQuoteTemplateField: {
      type: Boolean,
      default: false
    },
    fieldList: {
      type: Array,
      default() {
        return [];
      }
    },
    item: {
      type: Object,
      default() { return {}; }
    },
    formulaList: {
      type: Array,
      default() {
        return [{
          options: [], // 字段配置列宾
          name: '',
          isFocus: false,
          formula: ''
        }];
      }
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      mathTag: [
        { name: '×', id: -1 },
        { name: '÷', id: -1 },
        { name: '+', id: -1 },
        { name: '-', id: -1 },
        { name: '(', id: -1 },
        { name: ')', id: -1 },
        { name: 'avg', id: -1 },
        { name: '∑', id: -1 },
        { name: '△', id: -1 } // 总数
      ],
      quoteValue: '',
      quoteField: '',
      cascaderValue: [],
      dragOptions: {
        animation: 200,
        disabled: false,
        ghostClass: 'ghost'
      }
    };
  },
  methods: {
    openDialog() {
      this.dialogFormVisible = true;
    },
    deleteFormula(item, index) {
      item.options.splice(index, 1);
      if (this.lookInput) {
        this.inputFormula();
      }
    },
    filedSelect(item, option, name) {
      this.fieldList.forEach(i => {
        if (i.name === item[0]) {
          i.fieldInfo.forEach(j => {
            if (j.name === item[1]) {
              this.quoteField = j;
            }
          });
        }
      });
      this.toFocus(this.item);
      this.quoteFun({
        name: this.quoteField.name,
        id: this.quoteField.id,
        isVariate: true,
        postName: JSON.stringify(this.quoteField.name),
        sourceId: this.quoteField.id
      }, 'clearquoteField');
    },
    toFocus(item) {
      this.formulaList.forEach(i => {
        i.isFocus = false;
      });
      item.isFocus = true;
    },
    quoteFun(item, clear) {
      let value = item.id;
      if (clear === 'math') {
        this.toFocus(this.item);
        value = item.name;
      }
      if (!value || value === '') return;
      if (clear === 'clearQuoteValue') {
        const valuePointLen = value.toString().split('.')[1] ? value.toString().split('.')[1].length : 0;
        if (Number(value) > 1000000000) {
          this.$message({ type: 'warning', message: '请输入小于10位的数值' });
          return;
        } else if (valuePointLen > 5) {
          this.$message({ type: 'warning', message: '小数点后最多保留5位' });
          return;
        }
      }
      if (this.formulaList.length > 1) {
        let index = null;
        this.formulaList.forEach((i, idx) => {
          if (i.isFocus) index = idx;
        });
        if (index === null) {
          this.$message({ type: 'warning', message: '请点击需要引入到的公式' });
          return;
        }
        // 求和(∑)和平均数(avg)后面只能跟基础字段
        if (this.formulaList[index].options.length && (clear === 'clearQuoteValue' || clear === 'math')) {
          const len = this.formulaList[index].options.length;
          const tempid = this.formulaList[index].options[len - 1].id;
          if (tempid === '∑' || tempid === 'avg') {
            this.$message({ type: 'warning', message: '求和与求平均数后面只能跟基础字段' });
            return;
          }
        }
        this.formulaList[index].options.push(item);
      } else if (this.formulaList.length === 1) {
        // 求和(∑)和平均数(avg)后面只能跟基础字段
        if (this.formulaList[0].options.length && (clear === 'clearQuoteValue' || clear === 'math')) {
          const len = this.formulaList[0].options.length;
          const tempid = this.formulaList[0].options[len - 1].id;
          if (tempid === '∑' || tempid === 'avg') {
            this.$message({ type: 'warning', message: '求和与求平均数后面只能跟基础字段' });
            return;
          }
        }
        this.formulaList[0].options.push(item);
      }
      if (clear === 'clearQuoteValue') {
        this.quoteValue = '';
      }
      if (clear === 'clearquoteField') {
        this.quoteField = '';
        this.cascaderValue = [];
      }
      if (clear === 'clearquoteTemplateField') {
        this.quoteTemplateField = '';
      }
    },
    handleConfirm() {
      this.item.formula = this.item.options.reduce((res, item) => {
        return res + '' + item.name;
      }, '');
      this.dialogFormVisible = false;
    },
    handleClose() {
      this.item.oldOptions && (this.item.options = this.item.oldOptions);
      this.dialogFormVisible = false;
    }
  }
};
</script>

<style scoped lang="scss">
.formula-container {
  @include scrollBar($x: hidden, $y: auto);
  .formula-list {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
  }
  .formula-option {
    width:240px;
    height:32px;
    border-radius:4px;
    border:1px solid rgba(221,221,221,1);
    cursor: pointer;
    display: flex;
    overflow: hidden;
    align-items: center;
    &.active {
      border: 1px solid #406EFF;
    }
  }
}
.quote-container {
  .quote-list {
    display: flex;
    align-items: center;
    margin-top: 8px;
    .quote-title {
      margin-right: 40px;
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(102,102,102,1);
    }
    .quote-input {
      width: 240px;
      margin-right: 16px;
      & ::v-deep {
        .el-input__inner {
          width: 240px;
          height: 32px;
        }
      }
    }
    .quote-tag {
      width:24px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
    }
  }
}
/* .formula-scroll-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  & ::v-deep {
    .el-scrollbar__wrap {
      overflow-y: hidden;
      overflow-x: scroll;
      width: 100%;
      height: 150%;
    }
    .el-scrollbar__view {
      display: flex;
      height: 100%;
      align-items: center;
    }
    .el-scrollbar__bar.is-vertical {
      display: none;
    }
  }
} */
.formula-option-tag {
  padding: 0 8px;
  height:24px;
  background:rgba(239,243,251,1);
  border-radius:4px;
  color: #406EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  cursor: pointer;
  font-size: 12px;
  margin: 0 4px;
  white-space: nowrap;
}
.tooltip-formula-content {
  display: flex;
  flex-wrap: wrap;
}
.tip-text {
  font-size: 12px;
  color: #666;
  padding: 5px;
}
.operator-dialog{
  &::v-deep {
    .el-dialog{
      width: 450px !important;
    }
  }
  .btns{
    padding-top: 10px;
  }
  .width240 {
    width: 240px;
    & ::v-deep {
      .el-input__inner {
        width: 240px;
      }
      .el-input{
        width: 240px;
      }
    }
  }
  .center {
    display: flex;
    justify-content: center;
  }
}
.formula-list-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  .label {
    width: 56px !important;
    font-size: 14px;
    color: #666666;
    text-align: right;
    margin-right: 13px;
  }
  & ::v-deep {
    .el-input__inner {
      width: 240px;
      height: 32px;
    }
  }
  .formula-option {
    width:240px;
    height:32px;
    border-radius:4px;
    border:1px solid rgba(221,221,221,1);
    cursor: pointer;
    display: flex;
    overflow: hidden;
    align-items: center;
    &.active {
      border: 1px solid #406EFF;
    }
  }
}
.quote-list {
  display: flex;
  align-items: center;
  margin-top: 8px;
  .quote-title {
    margin-right: 40px;
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(102,102,102,1);
  }
  .quote-input {
    width: 240px;
    margin-right: 16px;
    & ::v-deep {
      .el-input__inner {
        width: 240px;
        height: 32px;
      }
    }
  }
  .quote-tag {
    width:24px;
    height:24px;
    background:rgba(239,243,251,1);
    border-radius:4px;
    color: #406EFF;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    cursor: pointer;
    font-size: 12px;
  }
}
</style>
<style lang="scss">
.tooltip-formula {
  padding: 0;
  max-width: 240px;
  border: 1px solid #ddd !important;
  .formula-option-tag {
    margin: 4px;
  }
  .popper__arrow {
    border-top-color: #ddd !important;
  }
}
</style>
